<?php

namespace App\Http\Controllers\Api;

use App\Models\StaffModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Facades\JWTAuth;
class LoginController extends Controller
{
    //员工登录
    public function Login(Request $request){
        try{
            $account = $request->input('account');
            $password = $request->input('password');
            $staffObj = StaffModel::where('account','=',$account)->first();
            if(!$staffObj){
                throw new \Exception('账号不存在');
            }

            if(!Hash::check($password,$staffObj->password)){
                throw new \Exception('密码错误');
            }

            $token = JWTAuth::fromUser($staffObj);

            unset($staffObj->admin_id);
            unset($staffObj->password);
            unset($staffObj->deleted_at);
            unset($staffObj->appid);
            unset($staffObj->updated_at);
            return response() -> json([
                'error_code' => 0,
                'msg' => '登录成功',
                'data' => [
                    'access_token' => $token,
                    'user'=>$staffObj,
                    'expires_in' => auth('api') -> factory()->getTTL() * 60
                ]
            ]);

        }catch(\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage(),
                'data' => null
            ]);
        }


    }

    //刷新token
    public function refresh_token(Request $request){

        try{
            $token = JWTAuth::refresh(JWTAuth::getToken());
            JWTAuth::setToken($token);
            //$request->user = JWTAuth::authenticate($token);
            return response() -> json([
                'error_code' => 0,
                'msg' => '刷新成功',
                'data' => $token
            ]);

        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage()
            ]);
        }

    }



}
